package org.huzhp.gateway.dynamic.rule;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: 动态限流服务
 * @Author: huzp
 * @CreateDate: 2020/3/12 13:27
 * @Version: 1.0
 */
@Service
public class DynamicRuleService {

    public Set<GatewayFlowRule> getRules() {
        return GatewayRuleManager.getRules();
    }

    public void add(GatewayFlowRule rule) throws Exception {
        Set<GatewayFlowRule> rules = getRules();
        rules.add(rule);
        boolean isLoad = GatewayRuleManager.loadRules(rules);
        if (!isLoad) {
            throw new Exception("加载失败");
        }
    }

    public void delete(String resource) {
        Set<GatewayFlowRule> rules = GatewayRuleManager.getRulesForResource(resource);
        if (rules.isEmpty()) {
            return;
        }
        GatewayRuleManager.loadRules(GatewayRuleManager.getRules().stream().filter(rule -> !rules.contains(rule)).collect(Collectors.toSet()));
    }

    public void delete(GatewayFlowRule rule) throws Exception {
        if (!GatewayRuleManager.isValidRule(rule)) {
            throw new Exception("删除失败");
        }
        GatewayRuleManager.loadRules(GatewayRuleManager.getRules().stream().filter(r -> !r.equals(rule)).collect(Collectors.toSet()));
    }
}
